/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.cspimp.esrz.service.impl;

import me.zhengjie.modules.cspimp.esrz.domain.Scl;
import me.zhengjie.modules.system.domain.AreaManage;
import me.zhengjie.modules.system.repository.AreaManageRepository;
import me.zhengjie.utils.*;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.cspimp.esrz.repository.SclRepository;
import me.zhengjie.modules.cspimp.esrz.service.SclService;
import me.zhengjie.modules.cspimp.esrz.service.dto.SclDto;
import me.zhengjie.modules.cspimp.esrz.service.dto.SclQueryCriteria;
import me.zhengjie.modules.cspimp.esrz.service.mapstruct.SclMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://docs.auauz.net
* @description 服务实现
* @author 黄星星
* @date 2020-06-26
**/
@Service
@RequiredArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class SclServiceImpl implements SclService {

    private final SclRepository sclRepository;
    private final SclMapper sclMapper;
    private final AreaManageRepository areaManageRepository;

    @Override
    public Map<String,Object> queryAll(SclQueryCriteria criteria, Pageable pageable){
        Page<Scl> page = sclRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(sclMapper::toDto));
    }

    @Override
    public List<SclDto> queryAll(SclQueryCriteria criteria){
        return sclMapper.toDto(sclRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    public SclDto findById(Long id) {
        Scl scl = sclRepository.findById(id).orElseGet(Scl::new);
        ValidationUtil.isNull(scl.getId(),"Scl","id",id);
        return sclMapper.toDto(scl);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SclDto create(Scl resources) {
        Long riskAreaId = resources.getRiskAreaId();
        String riskAreaName = resources.getRiskAreaName();
        if(null != riskAreaId){
            Optional<AreaManage> areaManageOptional = areaManageRepository.findById(riskAreaId);
            if(null != areaManageOptional){
                AreaManage areaManage = areaManageOptional.get();
                if(null != areaManage){
                    resources.setRiskAreaName(areaManage.getAreaName());
                }
            }
        }

        String jcxNumber = resources.getJcxNumber();
        if(StringUtils.isEmpty(jcxNumber)){
            resources.setJcxNumber("默认");
        }

        Long sclRiskLevelId = resources.getSclRiskLevelId();
        if(null == sclRiskLevelId){
            resources.setSclRiskLevelId(0L);
            resources.setSclRiskLevelCode("DEFAULT_RISK");
            resources.setSclRiskLevelName("默认");
        }
        return sclMapper.toDto(sclRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Scl resources) {
        Scl scl = sclRepository.findById(resources.getId()).orElseGet(Scl::new);
        ValidationUtil.isNull( scl.getId(),"Scl","id",resources.getId());
        scl.copy(resources);
        Long riskAreaId = resources.getRiskAreaId();
        String riskAreaName = resources.getRiskAreaName();
        if(null != riskAreaId){
            Optional<AreaManage> areaManageOptional = areaManageRepository.findById(riskAreaId);
            if(null != areaManageOptional){
                AreaManage areaManage = areaManageOptional.get();
                if(null != areaManage){
                    scl.setRiskAreaName(areaManage.getAreaName());
                }
            }
        }

        String jcxNumber = resources.getJcxNumber();
        if(StringUtils.isEmpty(jcxNumber)){
            scl.setJcxNumber("默认");
        }

        Long sclRiskLevelId = resources.getSclRiskLevelId();
        if(null == sclRiskLevelId){
            scl.setSclRiskLevelId(0L);
            scl.setSclRiskLevelCode("DEFAULT_RISK");
            scl.setSclRiskLevelName("默认");
        }
        sclRepository.save(scl);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            sclRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<SclDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (SclDto scl : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("所属公司", scl.getCid());
            map.put("所属项目", scl.getPid());
            map.put("创建时间", scl.getCreateTime());
            map.put("更新时间", scl.getUpdateTime());
            map.put("创建者", scl.getCreateBy());
            map.put("更新者", scl.getUpdateBy());
            map.put("设备名称", scl.getEquipName());
            map.put("风险区域主键", scl.getRiskAreaId());
            map.put("风险区域姓名", scl.getRiskAreaName());
            map.put("检查项数量", scl.getJcxNumber());
            map.put("风险等级主键", scl.getSclRiskLevelId());
            map.put("风险等级code", scl.getSclRiskLevelCode());
            map.put("风险等级名称", scl.getSclRiskLevelName());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}